package com.feihong.yw189.activity.denglu;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.activity.shouye.MainActivity;
import com.feihong.yw189.adapter.UOptionsAdapter;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.dialog.MyUsualyDialog;
import com.feihong.yw189.global.RequestTools;
import com.feihong.yw189.http.RefreshToken;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.localdb.DBHelper;
import com.feihong.yw189.localdb.LoginInfoHandler;
import com.feihong.yw189.message.LoginMessage;
import com.feihong.yw189.model.DBLoginInfoObj;
import com.feihong.yw189.model.User.LoginModel;
import com.feihong.yw189.paidan.qiangdanservice.LocationCallBack;
import com.feihong.yw189.paidan.qiangdanservice.LocationInfo;
import com.feihong.yw189.paidan.qiangdanservice.LocationToolsOnces;
import com.feihong.yw189.utils.UserLoginInfo;

import org.xutils.common.Callback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;


/**
 * Created by Sabirjan on 2017/11/13.
 * DX189.
 * 飞宏电子
 * 登录页面
 */
@RuntimePermissions
public class DengLuActivity extends BaseActivity  implements Handler.Callback{


    @BindView(R.id.logo)
    ImageView logo;
    @BindView(R.id.et_mobile)
    EditText etMobile;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.tv_checkVersion)
    TextView  tvVersion;
    @BindView(R.id.forget_password)
    TextView forgetPassword;

    @BindView(R.id.btn_login)
    TextView mLoginTv;

    ListView listView;
    @BindView(R.id.username_layout)
    LinearLayout parent;//浮动窗口依附布局
    @BindView(R.id.iv_clean_phone)
    ImageView down_but;
    private  View loginwindow;
    private PopupWindow mPopupWindow;// 浮动窗口
    private UOptionsAdapter mOptionsAdapter;//适配器
    private List<String> mUserNames;// 保存用户名
    private List<String> mPassWords;// 保存密码
    private List<DBLoginInfoObj> infoObjs;// 保存登陆信息数据对象
    private int pwidth;// 浮动宽口的宽度
    private int wwidth;// 浮动宽口的宽度
    private static final String TBL_LOGIN_INFO = "LoginInfo";// 用户登陆信息
    private boolean init_flag = false;// 浮动窗口显示标示符
    private Handler mHandler;// 处理消息更新UI

    String etmobliNumber, etPassWorld;

    private Unbinder unbinder;
    MyUsualyDialog   mydialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        unbinder = ButterKnife.bind(this);
        DengLuActivityPermissionsDispatcher.requestLocaitonPerWithCheck(this);
        initView();
    }

    @Override
    public void setTheme() {

    }

    // 初始化
    private void initView() {
        mUserNames = new ArrayList<>();
        mPassWords = new ArrayList<>();
        infoObjs = new ArrayList<DBLoginInfoObj>();
        mHandler = new Handler(this);

        tvVersion.setText("V"+AppUtils.getAppVersionName());
        mydialog=new MyUsualyDialog(this, R.layout.wait_item);
        mydialog.setCancelable(false);
        etMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if(TextUtils.isEmpty(s)){
                    etPassword.setText(null);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private LocationToolsOnces mLocationToolsOnces;
    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void requestLocaitonPer() {
          mLocationToolsOnces = new LocationToolsOnces(this, mLocationCallBack);
          mLocationToolsOnces.startLocation(0);
    }
    /**
     * 定位监听
     */
    LocationCallBack mLocationCallBack = new LocationCallBack() {
        @Override
        public void successGetLocation(LocationInfo info) {
            if (activityIsDestory()) {
                return;
            }
            String mLat,mLon;
            mLat = String.valueOf(info.getLatitude());
            mLon = String.valueOf(info.getLongitude());
            UserLoginInfo.getUserLoginInfoInstance().setLocationLat(mLat);
            UserLoginInfo.getUserLoginInfoInstance().setLocationLon(mLon);
        }

        @Override
        public void error(String error) {
            if (activityIsDestory()) {
                return;
            }
        }
    };

    @OnClick({R.id.btn_login, R.id.forget_password,R.id.iv_clean_phone})
    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                etmobliNumber = etMobile.getText().toString();
                etPassWorld = etPassword.getText().toString();
                if (!TextUtils.isEmpty(etmobliNumber) && !TextUtils.isEmpty(etPassWorld)) {
                    //登陆的时候,把用户名记录一下
                    mLoginTv.setEnabled(false);
                    login();
                } else if (TextUtils.isEmpty(etmobliNumber)) {
                    showErrorToast("用户名不能为空!");
                } else if (TextUtils.isEmpty(etPassWorld)) {
                    showErrorToast("密码不能为空!");
                }
                break;
            case R.id.forget_password:
                Intent intent = new Intent(DengLuActivity.this, ForgetPassWordActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_clean_phone:
                // 浮动地址下拉框按钮事件
                if (init_flag && mUserNames != null && mUserNames.size() > 0) {
                    // 显示浮动窗口
                    KeyboardUtils.hideSoftInput(this);
                    new Handler().postDelayed(() ->  mPopupWindow.showAsDropDown(parent, -18, 0),100);
                }
                break;
            default:
                break;

        }

    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    /**
     * 登录请求
     */
    private void login() {
        mydialog.show();
        mydialog.setWarningTxt(R.id.progress_layout_warning_tv,"正在登录");
        Context context = getApplication();
        Callback.Cancelable loginCallBack = App.getApp().getHttpTools().login(etmobliNumber, etPassWorld,context, new RequestCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                try{
                    LoginModel json = JSON.parseObject(result, LoginModel.class);
                    if(json != null){
                        //成功
                        if (json.getStatus() == 1) {
                            String token = json.getData().getToken();
                            RefreshToken refreshToken = RefreshToken.getInstance();
                            refreshToken.RefreshToken(token);
                            Intent intent = new Intent(DengLuActivity.this, MainActivity.class);
                            startActivity(intent);

                            // 登录成功将数据保存到SQLite中
                            ContentValues values = new ContentValues();
                            String userName = etMobile.getText().toString();
                            String passWord = etPassword.getText().toString();
                            values.put("UserName", userName);
                            values.put("PassWord", passWord);
                            DBHelper dbHelper = new DBHelper(DengLuActivity.this);
                            // 第一次登陆直接保存
                            if (mUserNames.size() == 0) {
                                dbHelper.insert(values, TBL_LOGIN_INFO);
                            } else {
                                // 标示符是否要插入
                                boolean flag = false;
                                // 判断当前用户名是否在数据库存在
                                LoginInfoHandler mHandler = LoginInfoHandler
                                        .create(DengLuActivity.this);
                                List<DBLoginInfoObj> info = mHandler.getLoginInfoObj();
                                for (int i = 0; i < info.size(); i++) {
                                    String username = info.get(i).getUserName();
                                    if (userName.equals(username)) {
                                        flag = true;
                                    }
                                }
                                if (!flag) {
                                    dbHelper.insert(values, TBL_LOGIN_INFO);
                                }
                            }
                            finish();
                        } else {
                            mLoginTv.setEnabled(true);
                            showToast(json.getInfo() + "");
                        }
                    }else{
                        mLoginTv.setEnabled(true);
                        showToast("数据出错,请重试");
                    }
                }catch (Exception ex){
                    mLoginTv.setEnabled(true);
                }
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mLoginTv.setEnabled(true);
                showToast(getResources().getString(R.string.connect_sever_error_toast));
            }
            @Override
            public void onCancelled(Callback.CancelledException cex) {
            }
            @Override
            public void onFinished() {
                mydialog.dismiss();
            }
        });
        RequestTools.addNewRequest(DengLuActivity.class.getName(),loginCallBack);

    }

    /**
     * 在此方法中初始化可以获得输入框的宽度，以便于创建同样宽的浮动窗口
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
        while (!init_flag) {
            // 初始化UI
            initWedget();
            // 初始化浮动窗口
            initPopuWindow();
            init_flag = true;
        }
    }

    /**
     * 初始化UI控件
     */
    private void initWedget() {

        // 浮动窗口的布局
        loginwindow = getLayoutInflater().inflate(
                R.layout.activity_denglu_pop, null);
        listView = loginwindow.findViewById(R.id.lv_pop);

        // 获取登陆数据
        getData();
        if(mUserNames.size() > 0){
            down_but.setVisibility(View.VISIBLE);
            etMobile.setText(mUserNames.get(0));
            etPassword.setText(mPassWords.get(0));
        }else {
            down_but.setVisibility(View.GONE);
        }

        // 获取地址输入框的宽度，用于创建浮动窗口的宽度
        int w = parent.getWidth()-30;
        int p = parent.getWidth()-100;
        pwidth = w;
        wwidth = p;
    }

    /**
     * 初始化浮动窗口
     */
    public void initPopuWindow() {


        // 初始化适配器
        mOptionsAdapter = new UOptionsAdapter(DengLuActivity.this,
                mUserNames, mHandler);

        // 定义一个浮动窗口，并设置
        mPopupWindow = new PopupWindow(loginwindow, pwidth, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        if(!mUserNames.isEmpty()){
            listView.setAdapter(mOptionsAdapter);
        }
    }

    /**
     * 获取登录用户名数据
     */
    private void getData() {
        //获取数据对象
        LoginInfoHandler mHandler = LoginInfoHandler.create(DengLuActivity.this);
        this.infoObjs = mHandler.getLoginInfoObj();
        for (int i = 0; i < infoObjs.size(); i++) {
            mUserNames.add(infoObjs.get(i).getUserName());
            mPassWords.add(infoObjs.get(i).getPassWord());
        }
    }
    /**
     * 处理浮动窗口传回来的数据
     * @param msg
     * @return
     */
    @Override
    public boolean handleMessage(Message msg) {
        // TODO Auto-generated method stub
        Bundle bundle = msg.getData();
        DBHelper dbHelper = new DBHelper(DengLuActivity.this);
        switch (msg.what) {
            case 1:// 根据返回的id，将数据显示在输入框中
                int sel_id = bundle.getInt("sel_id");
                int _id = infoObjs.get(sel_id).getID();
                String UserName = infoObjs.get(sel_id).getUserName();
                String PassWord = infoObjs.get(sel_id).getPassWord();
                // 先删除再插入
                dbHelper.del(_id, TBL_LOGIN_INFO);
                etMobile.setText(UserName);
                etPassword.setText(PassWord);
                mPopupWindow.dismiss();
                break;
            case 2:// 根据返回的ID，删除数据
                int del_id = bundle.getInt("del_id");
                int id = infoObjs.get(del_id).getID();
                dbHelper.del(id, TBL_LOGIN_INFO);
                mUserNames.remove(del_id);
                if(mUserNames.size() == 0){
                    etMobile.setText("");
                    etPassword.setText("");
                    down_but.setVisibility(View.GONE);
                }
                mOptionsAdapter.notifyDataSetChanged();
                break;
                default:break;
        }
        return false;
    }
    @Override
    protected void onDestroy() {
        // 清空请求
        RequestTools.removeRequest(DengLuActivity.class.getName());
        super.onDestroy();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }
}
